<template>
  <div class="authorization-management">
    <h1>授权管理</h1>
    <RouterLink to="/user-profile" class="back-btn">← 返回个人中心</RouterLink>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="errorMessage" class="error-message">
      <span class="error-icon">⚠️</span>
      <span class="error-text">{{ errorMessage }}</span>
    </div>

    <div v-if="!hasAccess" class="no-access">
      <span class="error-icon">🔒</span>
      <span class="error-text">您没有访问此页面的权限</span>
    </div>

    <div v-if="hasAccess && userInfo" class="authorization-container">
      <div class="authorization-card">
        <h2>已授权医生列表</h2>
        <div v-if="loadingAuthorizations" class="loading">加载授权列表中...</div>
        <div v-if="authorizationError" class="error-message">
          <span class="error-icon">⚠️</span>
          <span class="error-text">{{ authorizationError }}</span>
        </div>
        <el-table v-if="authorizations.length > 0" :data="authorizations" border style="width: 100%">
          <el-table-column prop="doctorId" label="医生ID"></el-table-column>
          <el-table-column prop="doctorName" label="医生姓名"></el-table-column>
          <el-table-column prop="authorizeTime" label="授权时间"></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <RouterLink v-if="row.authorizationId" :to="{ name: 'authorization-detail', params: { id: row.authorizationId } }">
                <el-button type="primary" size="small" icon="el-icon-info" style="margin-right: 8px;">详情</el-button>
              </RouterLink>
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="revokeAuthorization(row.authorizationId)"
                :loading="row.loading"
              >
                撤销授权
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else-if="!loadingAuthorizations && !authorizationError" class="no-authorizations">
          暂无授权记录
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { RouterLink, useRouter } from 'vue-router';
import axios from 'axios';
import { ElTable, ElTableColumn, ElButton } from 'element-plus';

const router = useRouter();
const userInfo = ref(null);
const loading = ref(true);
const errorMessage = ref('');
const hasAccess = ref(false);
const authorizations = ref([]);
const loadingAuthorizations = ref(false);
const authorizationError = ref('');

onMounted(() => {
  checkUserAccess();
});

// 检查用户权限
const checkUserAccess = async () => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser);
      // 只有角色为'用户'的可以访问
      hasAccess.value = userInfo.value.role === '用户';
      if (hasAccess.value) {
        fetchAuthorizations();
      }
    } else {
      errorMessage.value = '未找到用户信息，请先登录';
    }
  } catch (error) {
    errorMessage.value = '加载用户信息失败';
  } finally {
    loading.value = false;
  }
};

// 获取授权列表
const fetchAuthorizations = async () => {
  if (!userInfo.value || !userInfo.value.id) return;
  loadingAuthorizations.value = true;
  authorizationError.value = '';
  try {
    const response = await axios.get(`http://localhost:8080/api/authorizations/user/${userInfo.value.id}`);
    authorizations.value = response.data.data || [];
    console.log('授权数据结构:', authorizations.value);
  } catch (error) {
    authorizationError.value = '加载授权列表失败';
    console.error('获取授权列表失败:', error);
  } finally {
    loadingAuthorizations.value = false;
  }
};

// 撤销授权
const revokeAuthorization = async (authorizationId) => {
  if (!confirm('确定要撤销此授权吗？')) return;
   console.log("授权列表id："+authorizationId);
  try {
    await axios.delete(`http://localhost:8080/api/authorizations/${authorizationId}`);
    // 重新获取授权列表
    fetchAuthorizations();
    alert('授权已成功撤销');
  } catch (error) {
    alert('撤销授权失败: ' + (error.response?.data?.message || '未知错误'));
    console.error('撤销授权失败:', error);
  }
};
</script>

<style scoped>
.authorization-management {
  max-width: 800px;
  margin: 80px auto 2rem;
  padding: 2rem;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.back-btn {
  display: inline-block;
  margin-bottom: 1rem;
  color: #409eff;
  text-decoration: none;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message {
  color: #d43f3a;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.no-access {
  color: #e6a23c;
  background-color: #fdf6ec;
  border: 1px solid #ffe58f;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.error-icon {
  margin-right: 8px;
  font-size: 16px;
}

.authorization-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.authorization-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.no-authorizations {
  text-align: center;
  padding: 2rem;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.authorization-card .el-table {
  margin-top: 1rem;
}
</style>